package com.mgfireworks.mgplatform;

import cn.hn.java.summer.mvc.WebContext;
import com.mgfireworks.mgplatform.mgadmin.constants.Constant;
import com.mgfireworks.mgplatform.mgadmin.sys.FunctionService;
import com.mgfireworks.mgplatform.mgadmin.sys.OrganizationService;
import com.mgfireworks.mgplatform.mgadmin.sys.model.Function;
import com.mgfireworks.mgplatform.mgadmin.sys.model.Organization;
import com.mgfireworks.mgplatform.mgadmin.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class ActionInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	FunctionService functionService;
	@Autowired
	OrganizationService organizationService;
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);	
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//为上下文准备response
		WebContext.preperedResponse(response);

		String root=request.getContextPath();
		String url=request.getRequestURI();
		User user=WebContext.getSessionCookie(Constant.USER_SESSION_KEY,User.class);
		//登录检测
		if(user==null && !url.startsWith(root+"/login.html")){
			WebContext.redirectTo("/login.html");
		}

		if(user!=null){
            //获取用户功能菜单
            List<Function> functionList= functionService.getUserRoleFunctions(user);
			Organization org= organizationService.getOrganizationById(user.getOrgId());
			user.setOrg(org);
			request.setAttribute("currentUser",user);
            request.setAttribute("userRoleFunctions",functionList);
        }

		return super.preHandle(request, response, handler);
	}
}
